package com.mall.mallDemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.mallDemo.exception.ExceptionEnum;
import com.mall.mallDemo.exception.MyException;
import com.mall.mallDemo.mapper.CollectMapper;
import com.mall.mallDemo.pojo.Collect;
import com.mall.mallDemo.pojo.Product;
import com.mall.mallDemo.service.CollectService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Lii
 * @create 2022-06-15 9:35
 */
@Service("collectService")
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {
    @Autowired
    private CollectMapper collectMapper;

    @Override
    @Transactional
    public void addCollect(String userId, String productId) {
        Collect collect = new Collect();
        collect.setUserId(Integer.parseInt(userId));
        collect.setProductId(Integer.parseInt(productId));
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("product_Id",productId);
        // 先看看是否数据库中已存在
        Collect one = collectMapper.selectOne(queryWrapper);
        if (one != null) {
            throw new MyException(ExceptionEnum.SAVE_COLLECT_REUSE);
        }
        // 不存在，添加收藏
        collect.setCollectTime(new Date());
        int count = collectMapper.insert(collect);
        if (count != 1) {
            throw new MyException(ExceptionEnum.SAVE_COLLECT_ERROR);
        }
    }

    @Override
    public List<Product> getCollect(String userId) {
        List<Product> list = null;
        try {
            list = collectMapper.getCollect(userId);
            if (ArrayUtils.isEmpty(list.toArray())) {
                throw new MyException(ExceptionEnum.GET_COLLECT_NOT_FOUND);
            }
        } catch (MyException e) {
            e.printStackTrace();
            throw new MyException(ExceptionEnum.GET_COLLECT_ERROR);
        }
        return list;
    }

    @Override
    public void deleteCollect(String userId, String productId) {
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("product_id",productId);
        try {
            int count = collectMapper.delete(queryWrapper);
            if (count != 1) {
                throw new MyException(ExceptionEnum.DELETE_COLLECT_ERROR);
            }
        } catch (MyException e) {
            e.printStackTrace();
            throw new MyException(ExceptionEnum.DELETE_COLLECT_ERROR);
        }
    }
}
